import React, { useEffect, useState } from 'react';
import {
    Card,
    Table,
    Form,
    Select,
    Button,
    Space,
    Tag,
    Typography,
    message,
    Progress,
    Tooltip
} from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import styles from './index.module.css';
import {taskApi, TaskQueueResponseVO, TaskStatus} from "../../../services/api/task";
import {TASK_STATUS_CONFIG, TASK_TYPE, TASK_TYPE_TEXT} from "../../../constans/tasks";

const { Text } = Typography;
const { Option } = Select;

// 任务状态配置
const TASK_STATUS = {
    [TaskStatus.PENDING]: { text: '待处理', color: 'default' },
    [TaskStatus.PROCESSING]: { text: '处理中', color: 'processing' },
    [TaskStatus.COMPLETED]: { text: '已完成', color: 'success' },
    [TaskStatus.FAILED]: { text: '失败', color: 'error' }
};

const TaskListPage: React.FC = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<TaskQueueResponseVO[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });

    // 获取任务列表
    const fetchTasks = async (params: any) => {
        try {
            setLoading(true);
            const response = await taskApi.getTasksByPage(params);
            console.log('原始响应数据:', response);

            if (response?.data?.code === 200 && response?.data?.data) {
                const pageData = response.data.data;

                // 处理数据，解析 inputData
                const processedData = pageData.records.map((item: TaskQueueResponseVO) => {
                    try {
                        return {
                            ...item,
                            inputData: typeof item.inputData === 'string' ?
                                JSON.parse(item.inputData) : item.inputData
                        };
                    } catch (e) {
                        console.warn('解析inputData失败:', e);
                        return item;
                    }
                });

                console.log('处理后的数据:', processedData);

                setData(processedData);
                setPagination({
                    current: pageData.current,
                    pageSize: pageData.size,
                    total: pageData.total
                });
            } else {
                console.error('响应数据格式不正确:', response);
                message.error(response?.data?.message || '获取数据失败');
                setData([]);
                setPagination({ current: 1, pageSize: 10, total: 0 });
            }
        } catch (error) {
            console.error('获取任务列表失败:', error);
            message.error('获取数据失败，请重试');
            setData([]);
        } finally {
            setLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (newPagination: any, filters: any, sorter: any) => {
        console.log('分页变化:', newPagination);
        const params = {
            ...form.getFieldsValue(),
            current: newPagination.current,
            pageSize: newPagination.pageSize
        };
        fetchTasks(params);
    };

    // 处理查询
    const handleSearch = () => {
        const values = form.getFieldsValue();
        console.log('查询参数:', values);
        setPagination({ ...pagination, current: 1 });
        fetchTasks({ ...values, current: 1, pageSize: pagination.pageSize });
    };

    // 重置查询
    const handleReset = () => {
        form.resetFields();
        setPagination({ ...pagination, current: 1 });
        fetchTasks({ current: 1, pageSize: pagination.pageSize });
    };

    // 首次加载
    useEffect(() => {
        fetchTasks({
            current: 1,
            pageSize: 10
        });
    }, []);

    // 定义表格列
    const columns: ColumnsType<TaskQueueResponseVO> = [
        {
            title: '任务ID',
            dataIndex: 'taskId',
            width: 80,
        },
        {
            title: '任务类型',
            dataIndex: 'taskType',
            width: 120,
            render: (type: string) => (
                <Tag color="blue">
                    {TASK_TYPE_TEXT[type] || type}
                </Tag>
            )
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            render: (status: TaskStatus) => (
                <Tag color={TASK_STATUS_CONFIG[status].color}>
                    {TASK_STATUS_CONFIG[status].text}
                </Tag>
            )
        },
        {
            title: '进度',
            dataIndex: 'progress',
            width: 120,
            render: (progress: number) => (
                <Progress
                    percent={progress || 0}
                    size="small"
                    status={progress === 100 ? 'success' : 'active'}
                />
            )
        },
        {
            title: '输入数据',
            dataIndex: 'inputData',
            width: 200,
            ellipsis: true,
            render: (data: any) => {
                let displayData = data;
                try {
                    if (typeof data === 'string') {
                        displayData = JSON.parse(data);
                    }
                } catch (e) {
                    console.error('解析输入数据失败:', e);
                }

                return (
                    <Tooltip title={JSON.stringify(displayData, null, 2)}>
                        <Text ellipsis style={{ width: 180 }}>
                            {JSON.stringify(displayData)}
                        </Text>
                    </Tooltip>
                );
            }
        },
        {
            title: '结果链接',
            dataIndex: 'resultUrl',
            width: 200,
            render: (url: string) => url ? (
                <a href={url} target="_blank" rel="noopener noreferrer">
                    查看结果
                </a>
            ) : '-'
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            width: 180,
            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            width: 180,
            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
        }
    ];


    return (
        <div className={styles.container}>
            <Card bordered={false}>
                <Form
                    form={form}
                    layout="inline"
                    className={styles.queryForm}
                    onFinish={handleSearch}
                >
                    <Form.Item name="taskType" label="任务类型">
                        <Select
                            placeholder="请选择任务类型"
                            allowClear
                            style={{ width: 150 }}
                        >
                            {Object.entries(TASK_TYPE).map(([key, value]) => (
                                <Option key={value} value={value}>
                                    {TASK_TYPE_TEXT[value]}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="status" label="任务状态">
                        <Select
                            placeholder="请选择状态"
                            allowClear
                            style={{ width: 150 }}
                        >
                            {Object.entries(TASK_STATUS_CONFIG).map(([key, value]) => (
                                <Option key={key} value={Number(key)}>
                                    {value.text}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item>
                        <Space>
                            <Button
                                type="primary"
                                icon={<SearchOutlined />}
                                onClick={() => handleSearch()}
                            >
                                查询
                            </Button>
                            <Button
                                icon={<ReloadOutlined />}
                                onClick={() => handleReset()}
                            >
                                重置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>

                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="taskId"
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条数据`
                    }}
                    loading={loading}
                    onChange={handleTableChange}
                    scroll={{ x: 1300 }}
                    className={styles.table}
                />
            </Card>
        </div>
    );
};

export default TaskListPage;
